#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = "Administrator"
__name__="multiprocess_lock"
__date__="2016/9/14"
__time__="16:37"
"""
import multiprocessing

# 当多个进程需要访问共享资源的时候，lock可以用来避免访问的冲突。

def worker_with(lock,f):
    with lock:
        fs = open(f,"a+")
        fs.write("lock acquired via with\n")
        fs.close()

def worker_no_with(lock,f):
    lock.acquire()  # 锁定
    try:
        fs = open(f,"a+")
        fs.write('lock acquired directly\n')
        fs.close()
    finally:
        lock.release()  #释放锁

if __name__ == "__main__":
    f = "file.txt"
    lock = multiprocessing.Lock()   # 创建锁
    w = multiprocessing.Process(target=worker_with,args=(lock,f))
    nw = multiprocessing.Process(target=worker_no_with,args=(lock,f))

    w.start()
    nw.start()

    w.join()
    nw.join()

# 如果两个进程没用使用lock来同步，则他们对同一个文件的写操作可能会出现混乱。